package com.video.web.controller.app;

import com.alibaba.fastjson2.JSONObject;
import com.video.common.constant.Constants;
import com.video.common.constant.HttpStatus;
import com.video.common.core.controller.BaseController;
import com.video.common.core.domain.AjaxResult;
import com.video.common.core.page.TableDataInfo;
import com.video.common.exception.ServiceException;
import com.video.common.utils.SendSmsUtil;
import com.video.common.utils.StringUtils;
import com.video.framework.web.service.TokenService;
import com.video.video.domain.DCompany;
import com.video.video.domain.DEdition;
import com.video.video.domain.DKefu;
import com.video.video.domain.DUser;
import com.video.video.domain.GoodDownloadRecord;
import com.video.video.domain.app.dto.MemberDto;
import com.video.video.domain.app.dto.RePasswordDto;
import com.video.video.domain.app.dto.UserInfoDto;
import com.video.video.domain.dto.DCommissionRecordDto;
import com.video.video.domain.dto.DEchargeRecordDto;
import com.video.video.domain.dto.DKefuDto;
import com.video.video.domain.vo.DCommissionRecordQuery;
import com.video.video.domain.vo.KefuQuery;
import com.video.video.service.IDCommissionRecordService;
import com.video.video.service.IDCompanyService;
import com.video.video.service.IDEchargeRecordService;
import com.video.video.service.IDEditionService;
import com.video.video.service.IDKefuService;
import com.video.video.service.IDUserService;
import com.video.video.service.IGoodDownloadRecordService;
import com.video.web.service.AppDUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import java.util.List;
import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Api(tags = "会员")
@RestController
@RequestMapping("/app/user")
public class AppUserController extends BaseController {
  @Resource
  private IDUserService idUserService;//会员接口
  @Resource
  private TokenService tokenService;
  @Resource
  private AppDUserService appDUserService;
  @Resource
  private IDUserService userService;
  @Autowired
  private IDEchargeRecordService dEchargeRecordService;//充值接口
  @Autowired
  private IDCommissionRecordService dCommissionRecordService;//返佣
  @Autowired
  private IDCompanyService dCompanyService;
  @Autowired
  private IDKefuService dKefuService;
  @Autowired
  private IDEditionService dEditionService;
  @Autowired
  private IGoodDownloadRecordService goodDownloadRecordService;


  /**
   * 查询vip下载记录列表
   */
  @ApiOperation(value = "分页查询vip下载记录列表")
  @GetMapping("/getGoodDownloadRecordList")
  public TableDataInfo getGoodDownloadRecordList()
  {
    GoodDownloadRecord goodDownloadRecord=new GoodDownloadRecord();
    Long userId = getLoginUser().getUserId();
    goodDownloadRecord.setUid(String.valueOf(userId));
    startPage();
    List<GoodDownloadRecord> list = goodDownloadRecordService.selectGoodDownloadRecordList(goodDownloadRecord);
    return getDataTable(list);
  }

  @ApiOperation(value = "添加VIP下载视频记录")
  @ApiImplicitParams({
      @ApiImplicitParam(name = "goodId", value = "商品ID", dataType = "String", required = true)
  })
  @PostMapping("/addVipDownload")
  public AjaxResult add(String goodId)
  {
    GoodDownloadRecord goodDownloadRecord=new GoodDownloadRecord();
    Long userId = getLoginUser().getUserId();
    goodDownloadRecord.setUid(String.valueOf(userId));
    goodDownloadRecord.setUname(getLoginUser().getUsername());
    //获取商品信息
    if (StringUtils.isEmpty(goodDownloadRecord.getUid())) {
      throw new ServiceException("会员Id不能为空", 10077);
    }

    if (StringUtils.isEmpty(goodId)) {
      throw new ServiceException("商品Id不能为空", 10079);
    }
    goodDownloadRecord.setGid(goodId);
    return toAjax(goodDownloadRecordService.insertGoodDownloadRecord(goodDownloadRecord));
  }

  @ApiOperation(value = "获取VIP会员当天下载视频数量")
  @GetMapping("/getVipDownloadNum")
  public AjaxResult getVipDownloadNum() {
    Long userId = getLoginUser().getUserId();
    logger.info("根据id获取用户基本信息:{}", userId);
    return AjaxResult.success("成功", goodDownloadRecordService.getVipDownloadNum(String.valueOf(userId)));
  }

  @ApiOperation(value = "获取app版本信息")
  @GetMapping("/getEditionList")
  public TableDataInfo getEditionList(DEdition dEdition)
  {
    startPage();
    List<DEdition> list = dEditionService.selectDEditionList(dEdition);
    return getDataTable(list);
  }

  @ApiOperation(value = "根据id获取用户基本信息")
  @GetMapping("/detail")
  public AjaxResult detail() {
    Long userId = getLoginUser().getUserId();
    logger.info("根据id获取用户基本信息:{}", userId);
    return AjaxResult.success("成功", idUserService.selectDUserById(String.valueOf(userId)));
  }

  @ApiOperation(value = "修改个人信息")
  @PostMapping("/updateUserInfo")
  public AjaxResult updateUserInfo(@Validated UserInfoDto dto) {
    Long userId = getLoginUser().getUserId();
    logger.info("userId", userId);
    logger.info("修改个人信息", JSONObject.toJSONString(dto));
//    dto.setId(String.valueOf(userId));
    return AjaxResult.success("修改个人信息成功", appDUserService.updateUserInfo(dto));
  }

  @ApiOperation(value = "发送手机验证码")
  @ApiImplicitParams({
      @ApiImplicitParam(name = "mobile", value = "手机号", dataType = "String", defaultValue = "123456", required = true)
  })
  @GetMapping("/sendPhoneCode")
  public AjaxResult sendPhoneCode(String mobile) {
    logger.info("发送手机验证码:{}", mobile);
    String code = "123456";
    StringBuffer numStr=new StringBuffer();
    int num;
    for (int i = 0; i < 6; i++) {
      num=(int)(Math.random()*10);
      numStr.append(String.valueOf(num));
    }
    logger.info("验证码:"+numStr);
    code = numStr.toString();
    //缓存key
    String phoneToken = String.format(Constants.PHONE_CODE_TOKEN, mobile);
    if (phoneToken == null) {
      throw new ServiceException("校验手机验证码失败", 10020);
    }
    //调用短信发送接口
    SendSmsUtil.sendSms(mobile,"SMS_253910178",code);

    //存入redis字符,100秒
    tokenService.setCode(phoneToken, code, Constants.PHONE_CODE_TOKEN_TIME, TimeUnit.SECONDS);
    //调用短信-等待短信对接
    return AjaxResult.success("成功", Constants.PHONE_CODE_TOKEN_TIME);
  }

  @ApiOperation(value = "校验手机验证码")
  @ApiImplicitParams({
      @ApiImplicitParam(name = "mobile", value = "手机号码", dataType = "String", required = true),
      @ApiImplicitParam(name = "code", value = "验证码", dataType = "String", required = true)
  })
  @GetMapping("/checkPhoneCode")
  public AjaxResult checkPhoneCode(String mobile, String code) {
    logger.info("校验手机验证码:{},{}", mobile, code);

    //缓存key
    String phoneToken = String.format(Constants.PHONE_CODE_TOKEN, mobile, "");
    if (phoneToken == null) {
      throw new ServiceException("校验手机验证码失败", 10020);
    }
    return AjaxResult.success("校验手机验证码成功", tokenService.checkCode(phoneToken, code).booleanValue());
  }

  @ApiOperation(value = "修改密码")
  @PostMapping("/updatePassword")
  public AjaxResult updatePassword(@Validated RePasswordDto dto) {
    Long userId = getLoginUser().getUserId();
    dto.setId(String.valueOf(userId));
    logger.info("修改密码:{}", JSONObject.toJSONString(dto));
    return AjaxResult.success("修改密码成功", appDUserService.updatePassword(dto));
  }

  @ApiOperation(value = "找回密码")
  @PostMapping("/findPassword")
  public AjaxResult findPassword(@Validated RePasswordDto dto) {
    //根据手机号查询用户信息
    DUser dUserM=new DUser();
    dUserM.setMobile(dto.getMobile());
    List<DUser> userMlist=  userService.selectDUserAllList(dUserM);
    if(CollectionUtils.isEmpty(userMlist)){
      throw new ServiceException("用户信息不存在",10049);
    }

    if(userMlist.size() > 1){
      throw new ServiceException("用户信息存在多条",10049);
    }

    String userId = userMlist.get(0).getId();
    dto.setId(String.valueOf(userId));
    logger.info("修改密码:{}", JSONObject.toJSONString(dto));
    return AjaxResult.success("修改密码成功", appDUserService.updatePassword(dto));
  }


  @ApiOperation(value = "我的钱包-查询充值记录-支持分页）")
  @GetMapping("/getEchargeRecordList")
  public TableDataInfo getEchargeRecordList() {
    Long userId = getLoginUser().getUserId();
    startPage();
    List<DEchargeRecordDto> list = dEchargeRecordService.getEchargeRecordList(String.valueOf(userId));
    return getDataTable(list);
  }

  @ApiOperation(value = "我的佣金-查询返佣记录-支持分页）")
  @GetMapping("/getCommissionList")
  public TableDataInfo getCommissionList() {
    Long userId = getLoginUser().getUserId();
    DCommissionRecordQuery query=new DCommissionRecordQuery();
    query.setUserId(String.valueOf(userId));
    startPage();
    List<DCommissionRecordDto> list = dCommissionRecordService.selectDCommissionRecordList(query);
    return getDataTable(list);
  }

  @ApiOperation(value = "我的佣金(合伙人)-成员列表-支持分页）")
  @GetMapping("/getMemberList")
  public TableDataInfo getMemberList() {
    Long userId = getLoginUser().getUserId();
    startPage();
    List<MemberDto> list = idUserService.getMemberListByUserId(String.valueOf(userId));
    int count = 0;
    if(CollectionUtils.isNotEmpty(list)){
      for (MemberDto memberDto : list) {
        count=count+memberDto.getNumbers();
      }
      count=count+list.size();
    }

    TableDataInfo rspData = new TableDataInfo();
    rspData.setCode(HttpStatus.SUCCESS);
    rspData.setMsg("查询成功");
    rspData.setRows(list);
    rspData.setTotal(count);
    return rspData;
  }


  @ApiOperation(value = "联系我们")
  @GetMapping("/getCompany")
  public AjaxResult getCompany() {
    List<DCompany> list = dCompanyService.selectDCompanyList(new DCompany());
    return AjaxResult.success(list.get(0));
  }

  @ApiOperation(value = "查询会员提问列表")
  @GetMapping("/getProblemlist")
  public TableDataInfo getProblemlist()
  {
    KefuQuery query=new KefuQuery();
    Long userId = getLoginUser().getUserId();
    query.setUid(String.valueOf(userId));
    startPage();
    List<DKefuDto> list = dKefuService.selectDKefuDtoList(query);
    return getDataTable(list);
  }

  @ApiOperation(value = "会员提问接口")
  @GetMapping("/addProblem")
  public AjaxResult addProblem(String problem)
  {
    Long userId = getLoginUser().getUserId();
    DKefu dKefu=new DKefu();
    dKefu.setUid(String.valueOf(userId));
    dKefu.setProblem(problem);
    return toAjax(dKefuService.insertDKefu(dKefu));
  }
}
